<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useNavTagsStore } from '@/store'
import sortable from 'sortablejs'
import { layoutConfig } from '@/common/config'

onMounted(() => {
	initSortable()
	navTagsStore.setSortAttr()
})

const navTagsStore = useNavTagsStore()
const router = useRouter()
const activeTagName = ref('')
const { gap, navTagContainerHeigth } = layoutConfig

watch(
	() => navTagsStore.tags,
	(v) => {
		const name = v.find((v) => v.active)?.name
		if (name) activeTagName.value = name
	},
	{ immediate: true, deep: true }
)

function initSortable() {
	const dragArea = document.querySelector('.fast-navTags .el-tabs__nav')
	const ops = {
		animation: 100,
		dataIdAttr: 'itemId',
		onEnd: (_evt: any) => {
			// console.log(sortableInstance.toArray());
			setTimeout(() => {
				navTagsStore.setSort(sortableInstance.toArray())
			}, 100)
		},
	}
	//初始化
	const sortableInstance = sortable.create(dragArea, ops)
}
function bindGo(panel: any) {
	// console.log('hhhh',panel)
	router.push(navTagsStore.tags.find((v) => v.name == panel.paneName)!.fullPath)
}
function delTag(k: string) {
	navTagsStore.deleteTag(navTagsStore.tags.findIndex((v) => v.name == k))
}
</script>

<template>
	<el-tabs class="fast-navTags" v-model="activeTagName" type="card"  @tab-remove="delTag" @tab-click="bindGo">
		<el-tab-pane v-for="(item, index) in navTagsStore.tags" :key="item.name" :closable="!item.affix" :itemId="item.name" :label="item.title" :name="item.name">
			<template #label>
				<el-dropdown trigger="contextmenu" :key="item.name" :itemId="item.name">
					<!-- @click="bindGo(item)"  -->
					<div :class="{ tag: true, active: item.active }">
						<span class="title">{{ item.title }}</span>
						<!-- <el-icon style="font-size: 13px" v-if="!item.affix" @click.stop="bindCloseTag(index)"><Close /></el-icon> -->
					</div>
					<template #dropdown>
						<el-dropdown-menu>
							<el-dropdown-item @click="navTagsStore.deleteTag(index)" :disabled="item.affix">关闭当前</el-dropdown-item>
							<el-dropdown-item @click="navTagsStore.clearRightTags(index)">关闭右侧</el-dropdown-item>
							<el-dropdown-item @click="navTagsStore.clearLeftTags(index)" :disabled="index==0">关闭左侧</el-dropdown-item>
							<el-dropdown-item @click="navTagsStore.clearOtherTags(index)">关闭其他</el-dropdown-item>
							<el-dropdown-item @click="navTagsStore.clearTags(false)">关闭所有</el-dropdown-item>
						</el-dropdown-menu>
					</template>
				</el-dropdown>
			</template>
		</el-tab-pane>
	</el-tabs>
</template>

<style scoped lang="scss">
.fast-navTags {
	margin-left: v-bind(gap);

	:deep(.el-tabs__header) {
		height: v-bind(navTagContainerHeigth);
		margin: 0;
	}

	:deep(.el-tabs__item) {
		height: calc(v-bind(navTagContainerHeigth) - 2px);
	}
}
</style>
